package cc.fs.zhihu.ui.adapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import cc.fs.zhihu.AppContext
import cc.fs.zhihu.R
import cc.fs.zhihu.beans.FileBean
import cc.fs.zhihuapp.utils.bindView
import java.io.File
import java.util.*

/**
 * Created by fostion on 2015/10/15.
 */
class SelectFileAdapter(private val list: ArrayList<FileBean>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val TYPE_DIR: Int = 0;
    private val TYPE_FILE: Int = 1;
    var onClick:((FileBean) -> Unit) ? = null

    override fun getItemCount(): Int {
        return list.size()
    }

    override fun getItemViewType(position: Int): Int {
        if (list.get(position).category!!.equals("dir")) {
            return TYPE_DIR
        }
        return TYPE_FILE
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? {
        if (viewType == TYPE_DIR) {
            val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_select_dir, parent, false)
            return DirViewHolder(view)
        } else {
            val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_select_file, parent, false)
            return FileViewHolder(view)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        if (holder is DirViewHolder) {
            holder.setData(list.get(position))
        } else if (holder is FileViewHolder) {
            holder.setData(list.get(position))
        }
    }

    private inner class DirViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val img: ImageView by bindView(R.id.img)
        val title: TextView by bindView(R.id.title)
        val detail: TextView by bindView(R.id.detail)

        fun setData(file: FileBean) {
            title.text = file.name
            //过滤文件夹
            detail.text = "文件数:"+ File(file.path).listFiles().filter { file -> !file.isDirectory }.size()
            itemView.setOnClickListener { onClick?.invoke(file) }
        }
    }

    private inner class FileViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val img: ImageView by bindView(R.id.img)
        val title: TextView by bindView(R.id.title)
        fun setData(file: FileBean) {
            title.text = file.name
        }
    }

}